#include "DBTOOLS.h"
#include <crtdbg.h>
#include <stdlib.h>
#include <ocidfn.h>
#include "oci.h"
#include "FMConnection.h"
#include "ErrorCheck.h"
#include <orl.h>


DBTOOLS::DBTOOLS(void)
{
}


DBTOOLS::~DBTOOLS(void)
{
}

//copy incoming property text to internal variable
void DBTOOLS::CopyPropertyValue( char **pInternal,char *pExternal )
{
	if (*pInternal)
	{
		free(*pInternal);
	} 
	size_t iSize=(strlen(pExternal)+1);
	*pInternal=(char *)malloc(iSize*sizeof(char));
	strcpy_s(*pInternal,iSize,pExternal);

}

sb4 DBTOOLS::GetSizeFromOraDataType( ub2 OraDataType,void *VarValue )
{
	sb4 VarSize=0;
	switch(OraDataType)
	{
	case SQLT_INT:
		VarSize=sizeof(int);
		break;

	case SQLT_BDOUBLE:
		VarSize=sizeof(double);
		break;

	case SQLT_NUM:
	case SQLT_VNU:
		VarSize=OCI_NUMBER_SIZE;
		break;

	case SQLT_STR:
		if(VarValue)
		{
			VarSize=(sb4)strlen((char *)VarValue)* sizeof(char);
		}
		break;

	case SQLT_RSET:
		VarSize=0;//sizeof(OCIStmt*);
		break;

	default:
		//note: 
		throw "unimplemented SQL data type for command execution";
		break;
	}

	return VarSize;
}

//convert WCHAR to multi byte char
char* DBTOOLS::ConvertWCHAR2CHAR(char *source)
{
	int n;
	size_t SourceLengh=strlen(source);
	char *Dest = (char *)malloc( MB_CUR_MAX*(SourceLengh+1));

	char *SourceTmp=source;
	char *destTmp=Dest;

	for (int i=0;i<SourceLengh;i++)
	{
		wctomb_s( &n, destTmp, MB_CUR_MAX, *SourceTmp );
		SourceTmp++;
		destTmp+=MB_CUR_MAX;
	}
	wctomb_s( &n, destTmp, MB_CUR_MAX, char("\0"));

	return Dest;
}

//convert oci number to ID
bool DBTOOLS::ConvertNumberToID( OCIError* pErr,OCINumber *pNum,unsigned __int64& val )
{
	return ConvertNumberToInt(pErr,pNum,sizeof(unsigned __int64),false,&val);
}

bool DBTOOLS::ConvertNumberToInt( OCIError* pErr,OCINumber *pNum,unsigned int ValSize,bool bSigned,void* pVal )
{
	sword status=OCINumberToInt(pErr,pNum,ValSize,bSigned?OCI_NUMBER_SIGNED:OCI_NUMBER_UNSIGNED,pVal);
	CheckErr(pErr,status);
	if (status!=OCI_SUCCESS)
	{
		return false;
	} 
	else
	{
		return true;
	}
}

bool DBTOOLS::ConvertNumberToDouble( OCIError* pErr,OCINumber *pNum,unsigned int ValSize,void* pVal )
{
	sword status=OCINumberToReal(pErr,pNum,ValSize,pVal);
	CheckErr(pErr,status);
	if (status!=OCI_SUCCESS)
	{
		return false;
	} 
	else
	{
		return true;
	}
}
